var MY_MAP = (function() {

	var pageName='';

	var map = new BMap.Map("container", { enableMapClick: false});
	
	function initMap(page) {

		pageName = page;

		//机构统查 地图标记点 下拉选择行业类型
		var institutionsType=document.getElementById("institutionsType");
		if(institutionsType != null) {
			institutionsType.onchange=function(){
				var value = $(this).children('option:selected').val();
				if (value == -1) {
					value = '';
				}
				loadMapInfo(value);
			}
		}

		function getAera() {
            var boundaries = "120.220459, 30.236029;120.205312, 30.247435;120.197723, 30.251454;120.192586, 30.252134;120.193895, 30.255841;120.194136, 30.257266;120.194658, 30.263239;120.19108, 30.263691;120.181456, 30.26364;120.174859, 30.263943;120.168946, 30.264137;120.164951, 30.264037;120.164566, 30.264126;120.164745, 30.263748;120.165128, 30.262292;120.166116, 30.26212;120.166549, 30.261451;120.169205, 30.257385;120.168899, 30.256577;120.168294, 30.256426;120.167075, 30.255575;120.166176, 30.254842;120.165751, 30.254037;120.166039, 30.253646;120.165485, 30.253735;120.164651, 30.252444;120.165182, 30.2521;120.1662, 30.251627;120.164109, 30.249651;120.161443, 30.247053;120.160883, 30.24548;120.161033, 30.243706;120.160806, 30.242084;120.161478, 30.239703;120.162493, 30.23909;120.16462, 30.238417;120.166635, 30.236759;120.166267, 30.23568;120.166738, 30.234532;120.166117, 30.231871;120.166606, 30.230447;120.166249, 30.22918;120.165235, 30.227358;120.164275, 30.225891;120.163408, 30.22496;120.162848, 30.223941;120.161741, 30.222711;120.161323, 30.221672;120.160586, 30.222957;120.160586, 30.223693;120.159646, 30.223546;120.15856, 30.222618;120.157283, 30.221733;120.156331, 30.220625;120.155607, 30.220268;120.154654, 30.218908;120.153463, 30.21857;120.149631, 30.218598;120.148464, 30.219069;120.147713, 30.220253;120.146669, 30.220166;120.146605, 30.218466;120.147732, 30.215329;120.149024, 30.213049;120.149575, 30.212584;120.14987, 30.212561;120.147618, 30.211412;120.145625, 30.210687;120.145824, 30.210014;120.14576, 30.209387;120.145613, 30.208566;120.145291, 30.207199;120.144662, 30.206129;120.143877, 30.205303;120.144167, 30.20386;120.150505, 30.200547;120.182356, 30.211494;120.212027, 30.227652";
            var ply = new BMap.Polygon(boundaries, {strokeWeight: 0.01, strokeColor: "#999", fillColor: ""});
            map.addOverlay(ply);

            //添加环形遮罩层
            addMask(boundaries);

			var centerPoint = new BMap.Point(120.188169,30.234906);
			map.centerAndZoom(centerPoint, 15);

            //首次加载 标记点
            if(institutionsType != null) {
                var value = $("#institutionsType option:selected").val();
                if (value == -1) {
                	value = '';
				}
                loadMapInfo(value);
            }
		}

		function addMask(boundaries){
			var boundariesNew = boundaries;
			var tempArr = boundaries.split(";");
			if(tempArr.length > 0) {
				boundariesNew += ";" + tempArr[0] + ";";
			}

			var EN_JW = "180, 90;";//东北角
			var NW_JW = "-180,  90;";//西北角
			var WS_JW = "-180, -90;";//西南角
			var SE_JW = "180, -90;";//东南角

			boundariesNew += SE_JW + WS_JW + NW_JW + EN_JW + SE_JW;

			var ply = new BMap.Polygon(boundariesNew, {
				strokeColor: "none",
				fillColor: "rgba(0,0,0,0.5)",
				fillOpacity: 1,
				strokeOpacity: 0.5
			}); //建立多边形覆盖物
			map.addOverlay(ply);
		}

		function getRegion() {
			var bdary = new BMap.Boundary();
			var tempArr = countyArr;
			for(var i=0; i < tempArr.length; i++) {
				bdary.get(tempArr[i].name, function (rs) {
					var count = rs.boundaries.length;
					if(count <= 0) {
						return;
					}
					for(var i = 0; i < count; i++){
						//给目标行政区划添加边框，其实就是给目标行政区划添加一个没有填充物的遮罩层
						var boundaries = rs.boundaries[i];
						var ply = new BMap.Polygon(boundaries, {strokeWeight: 2, strokeColor: "#999", fillColor: ""});
						map.addOverlay(ply);
						// citySetLabel(new BMap.Point(tempArr[i]['cp'][0], tempArr[i]['cp'][1]) , tempArr[i]['name'])
					}
				});
			}
		}

		function citySetLabel(cityCenter, cityName) {
			var label = new BMap.Label(cityName, {
				offset: new BMap.Size(-20, -10),
				position: cityCenter
			});
			label.setStyle({
				border: 'none',
				background: 'transparent',
				'font-size': '0.25rem',
				color: '#fff',
			});
			map.addOverlay(label);
		}

		//获取地图坐标点
		function loadMapInfo(type) {
			$.ajax({
				type: "POST",
				url: "invs_home_page.do/load_map_info",
				data: {institutionType : type},
				success: function(data) {
					WeKnow.closeLoading();
					if (!WeKnow.filterAjaxResult(data)) return false; // session过期check

					if (data.errorcode == 0) {
						loadMarkerClick(data.mapInfo);
					} else if (data.errorcode == -1 ) {
						WeKnow.errorMsg( data.errMsg );
					} else {
						WeKnow.systemMsg('查询失败，请重新登录');
					}
				}
			});
		}

		getAera();
		setMapStyle();

		map.enableScrollWheelZoom();
	}

	//加载标注点 点击显示信息窗口
	function loadMarkerClick(points) {

		var page = "";
		switch (pageName) {
			case "institution_review":
				page = "institutionReview";
				break;
			case "prescription_supervision":
				page = "prescriptionSupervision";
				break;
			case "account_supervision":
				page = "accountSupervision";
				break;
			default:
				return;
				break;
		}

		//循环建立标注点
		removeMarker();

		var icon = getMarkerIcon();
		for(var i=0; i < points.length; i++) {
			var longitude = points[i].longitude;
			var latitude = points[i].latitude;
			if(longitude && latitude) {
				var point = new BMap.Point(longitude, latitude); //将标注点转化成地图上的点
				var marker = new BMap.Marker(point, {icon:icon}); //将点转化成标注点
				map.addOverlay(marker);  //将标注点添加到地图上
				//添加监听事件
				(function() {
					var thePoint = points[i];
					marker.addEventListener("click",
						//显示信息的方法
						function(e) {
							var infowindow = document.getElementById( "infoWindow");
							var sContent =
								"<div style='padding: 0.2rem 0.3rem 0.1rem 0.3rem; color: #2C7EEC; font-size: 0.2rem;'>"
								+ "<ul>"
								+ "<li class='infoWindow_li'>" +"<span>名称：</span>" + thePoint.institutionName + "</li>"
								+ "<li class='infoWindow_li'>" +"<span>地址：</span>" + thePoint.address + "</li>"
								+ "<a href='javascript:void(0)' " +"onclick=MY_HOME_PAGE_COMMON.jumpToInstitutionDetail('"+page+"','"+thePoint.id + "','"+thePoint.institutionName + "')>"
								+ "<li class='infoWindow_li' style='justify-content: flex-end;font-size: 0.175rem'>" +"<span id='infoWindowLogin'>查看更多>></span></li>"
								+ "</a>"
								+"</ul>"
								+"</div>";
							infowindow.innerHTML = "";

							$("#infoWindow").append(sContent);
							pos(infowindow, 0, -fontChart(2), e);

							infowindow.style.display= "inline";
						});
				})();
			}
		}
	}

	//加载标注点
	function loadMarker(points) {

		//循环建立标注点
		removeMarker();

		var icon = getMarkerIcon();
		for(var i=0; i < points.length; i++) {
			var longitude = points[i].longitude;
			var latitude = points[i].latitude;
			if(longitude && latitude) {
				var point = new BMap.Point(longitude, latitude); //将标注点转化成地图上的点
				var marker = new BMap.Marker(point, {icon:icon}); //将点转化成标注点
				map.addOverlay(marker);  //将标注点添加到地图上
				//添加监听事件
				(function() {
					var thePoint = points[i];
					/*marker.addEventListener("click",
						//显示信息的方法
						function() {
							showInfo(this,thePoint);
						});*/
					marker.addEventListener("mouseover", function(e) {
						var infowindow = document.getElementById( "infoWindow");
						var sContent =
							"<div style='padding: 0.2rem 0.3rem 0.1rem 0.3rem; color: #2C7EEC; font-size: 0.2rem;'>"
							+ "<ul>"
							+ "<li class='infoWindow_li'>" +"<span>名称：</span>" + thePoint.institutionName + "</li>"
							+ "<li class='infoWindow_li'>" +"<span>地址：</span>" + thePoint.address + "</li>"
							+"</ul>"
							+"</div>";
						infowindow.innerHTML = "";

						$("#infoWindow").append(sContent);
						if (document.getElementById("exit_full").style.display == "none") {
							pos(infowindow, 0, -150, e);
						} else {
							pos(infowindow, 0, -150, e);
						}

						infowindow.style.display= "inline";
					});

					//鼠标离开时
					marker.addEventListener("mouseout", function(e) {
						// hideInfo(this);
						document.getElementById( "infoWindow").style.display = "none";
					});
				})();
			}
		}
	}

	//加载多种样式标注点
	function loadMultipleMarker(pointsArray) {
		//循环建立标注点
		removeMarker();
		for(var i=0; i < pointsArray.length; i++) {
			var points = pointsArray[i];
			var icon = getMarkerIcon(i);
			for(var j=0; j < points.length; j++) {
				var longitude = points[j].longitude;
				var latitude = points[j].latitude;
				if(longitude && latitude) {
					var point = new BMap.Point(longitude, latitude); //将标注点转化成地图上的点
					var marker = new BMap.Marker(point, {icon:icon}); //将点转化成标注点
					map.addOverlay(marker);  //将标注点添加到地图上
					//添加监听事件
					(function() {
						var thePoint = points[j];
						/*marker.addEventListener("click",
							//显示信息的方法
							function() {
								showInfo(this,thePoint);
							});*/
						marker.addEventListener("mouseover", function(e) {
							var infowindow = document.getElementById( "infoWindow");
							var sContent =
								"<div style='padding: 0.2rem 0.3rem 0.1rem 0.3rem; color: #2C7EEC; font-size: 0.2rem;'>"
								+ "<ul>"
								+ "<li class='infoWindow_li'>" +"<span>名称：</span>" + thePoint.institutionName + "</li>"
								+ "<li class='infoWindow_li'>" +"<span>地址：</span>" + thePoint.address + "</li>"
								+"</ul>"
								+"</div>";
							infowindow.innerHTML = "";

							$("#infoWindow").append(sContent);
							if (document.getElementById("exit_full").style.display == "none") {
								pos(infowindow, 0, -150, e);
							} else {
								pos(infowindow, 0, -150, e);
							}

							infowindow.style.display= "inline";
						});

						//鼠标离开时
						marker.addEventListener("mouseout", function(e) {
							// hideInfo(this);
							document.getElementById( "infoWindow").style.display = "none";
						});
					})();
				}
			}
		}
	}

	//加载标注点
	function loadDisplayMarker(points) {

		//循环建立标注点
		removeMarker();

		var icon = getMarkerIcon();
		for(var i=0; i < points.length; i++) {
			var  posArr = points[i].position.split("|");
			if (posArr.length == 2) {
				var longitude = posArr[0];
				var latitude = posArr[1];
				if(longitude && latitude) {
					var point = new BMap.Point(longitude, latitude); //将标注点转化成地图上的点
					var marker = new BMap.Marker(point, {icon:icon}); //将点转化成标注点
					map.addOverlay(marker);  //将标注点添加到地图上
					//添加监听事件
					(function() {
						var thePoint = points[i];
						marker.addEventListener("click",
                            //显示信息的方法
                            function(e) {
								var infowindow = document.getElementById( "infoWindow");
								var sContent =
									"<div style='padding: 0.2rem 0.3rem 0.1rem 0.3rem; color: #2C7EEC; font-size: 0.2rem;'>"
									+ "<ul>"
									+ "<li class='infoWindow_li'>" + thePoint.name + "</li>"
									+ "<li class='infoWindow_li'>" +"<span>地址：</span>" + thePoint.address + "</li>"
									+ "<li class='infoWindow_li_illegal'>" +"<span>诊疗行为异常 (</span>" + thePoint.preIllegalCnt + ")</li>"
									+ "<li class='infoWindow_li_illegal'>" +"<span>卫生消毒异常 (</span>" + thePoint.accIllegalCnt + ")</li>"
									+ "<li class='infoWindow_li_illegal'>" +"<span>质控评分 (</span>" + "-" + ")</li>"
									+ "<a href='javascript:toLogin()'>"
									+ "<li class='infoWindow_li' style='justify-content: flex-end;font-size: 0.175rem'>" +"<span id='infoWindowLogin'>查看更多>></span></li>"
									+ "</a>"
									+"</ul>"
									+"</div>";
								infowindow.innerHTML = "";

								$("#infoWindow").append(sContent);
								pos(infowindow, 0, -fontChart(3.125), e);

								infowindow.style.display= "inline";
                            });
					})();
				}
			}
		}
	}

	//移除标记点
	function removeMarker() {
		var allOverlay = map.getOverlays();
		for (var i = 0; i < allOverlay.length; i++) {
			if (allOverlay[i].toString() == "[object Marker]") {
				map.removeOverlay(allOverlay[i]);
			}
		}
	}

	var pos = function (o, x, y, event) {  //鼠标定位赋值函数
		var posX = 0, posY = 0;  //临时变量值
		var e = event || window.event;  //标准化事件对象
		if (e.pageX || e.pageY) {  //获取鼠标指针的当前坐标值
			posX = e.pageX;
			posY = e.pageY;
		} else if (e.clientX || e.clientY) {
			posX = event.clientX + document.documentElement.scrollLeft + document.body.scrollLeft;
			posY = event.clientY + document.documentElement.scrollTop + document.body.scrollTop;
		}
		// o.style.position = "absolute";  //定义当前对象为绝对定位
		o.style.top = (posY + y) + "px";  //用鼠标指针的y轴坐标和传入偏移值设置对象y轴坐标
		o.style.left = (posX + x) + "px";  //用鼠标指针的x轴坐标和传入偏移值设置对象x轴坐标
	}

	function showInfo(thisMarker,point) {

		//获取点的信息
		var sContent = '';
		switch (pageName) {
			case "institution_review"://机构统查
			case "prescription_supervision"://政府监督 => 行政执法 => 诊疗行为监管
			case "account_supervision"://政府监督 => 行政执法 => 卫生消毒监管
			case "comprehensiveApplication":
				sContent =
					'<ul style="color: rgba(44,126,236,0.8);">'
					+'<li style="line-height: 26px;font-size: 15px;">'
					+'<span style="width: 50px;display: inline-block;">名称：</span>' + point.institutionName + '</li>'
					+'<li style="line-height: 26px;font-size: 15px;">'
					+'<span style="width: 50px;display: inline-block;">地址：</span>' + point.address + '</li>'
					+'</ul>';
				break;
			default:
				return;
		}

		var infoWindow = new BMap.InfoWindow(sContent); //创建信息窗口对象
		thisMarker.openInfoWindow(infoWindow); //图片加载完后重绘infoWindow
	}

	//标记点背景图
	function getMarkerIcon(i) {
		var icon;
		switch (pageName) {
			case "institution_review":
				icon = new BMap.Icon("plugins/home_page_common/images/map/yellow_bubble.png", new BMap.Size(30, 30));
				break;
			case "prescription_supervision"://政府监督 => 行政执法 => 诊疗行为监管
				icon = new BMap.Icon("plugins/home_page_common/images/map/blue_bubble.png", new BMap.Size(30, 30));
				break;
			case "account_supervision"://政府监督 => 行政执法 => 卫生消毒监管
				icon = new BMap.Icon("plugins/home_page_common/images/map/yellow_bubble.png", new BMap.Size(30, 30));
				break;
			case "comprehensive_application"://综合评价
				if (i ==0) {  //台账异常标注
					icon = new BMap.Icon("plugins/home_page_common/images/map/blue_bubble.png", new BMap.Size(30, 30));
				} else if (i ==1){	//未完成自查标注
					icon = new BMap.Icon("plugins/home_page_common/images/map/purple_bubble.png", new BMap.Size(30, 30));
				} else if (i ==2){	//信用评价差标注
					icon = new BMap.Icon("plugins/home_page_common/images/map/pink_bubble.png", new BMap.Size(30, 30));
				} else if (i ==3){ //处方异常标注
					icon = new BMap.Icon("plugins/home_page_common/images/map/yellow_bubble.png", new BMap.Size(30, 30));
				}
				break;
			case "comprehensive_display":
				icon = new BMap.Icon("plugins/home_page_common/images/map/yellow_bubble.png", new BMap.Size(30, 30));
				break;
			default:
				return;
		}

		// icon.setImageSize(new BMap.Size(30,30));//设置图标大小
		return icon;
	}

	//设置地图样式
	function setMapStyle() {
		map.setMapStyleV2({
			styleJson:eval("mapStyle")
		});
	}

	//自适应字体大小
	function fontChart(res) {
		//获取到屏幕的宽度
		var clientWidth =
			window.innerWidth ||
			document.documentElement.clientWidth ||
			document.body.clientWidth;
		if (!clientWidth) return; //报错拦截：
		var fontSize = 80 * (clientWidth / screen.width);
		return res * fontSize;
	}

	return {
		initMap:initMap,
		loadMarker:loadMarker,
		loadMultipleMarker:loadMultipleMarker,
		loadDisplayMarker:loadDisplayMarker,
		loadMarkerClick:loadMarkerClick,
	}
})();

$(document).ready(function() {
	document.onmousedown=function(event){
		if ($(event.target).attr('id') == 'infoWindowLogin') {
			return;
		}

		var element = document.getElementById( "infoWindow");
		if (element && element.style.display == 'inline') {
			element.style.display = "none";
		}
	};
	document.onkeydown=function(event){
		if ($(event.target).attr('id') == 'infoWindowLogin') {
			return;
		}

		var element = document.getElementById( "infoWindow");
		if (element && element.style.display == 'inline') {
			element.style.display = "none";
		}
	};
});